import React, { useEffect, useRef, useState } from 'react';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { MapPin, Utensils, Camera, Route, Home, Eye, EyeOff } from 'lucide-react';

// 修复 Leaflet 默认图标问题
delete (L.Icon.Default.prototype as any)._getIconUrl;
L.Icon.Default.mergeOptions({
  iconRetinaUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon-2x.png',
  iconUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-icon.png',
  shadowUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/images/marker-shadow.png',
});

interface MapProps {
  className?: string;
}

interface LayerConfig {
  id: string;
  name: string;
  icon: React.ReactNode;
  color: string;
  visible: boolean;
}

const Map: React.FC<MapProps> = ({ className = '' }) => {
  const mapRef = useRef<HTMLDivElement>(null);
  const mapInstanceRef = useRef<L.Map | null>(null);
  const layerGroupsRef = useRef<{ [key: string]: L.LayerGroup }>({});
  const [selectedPoi, setSelectedPoi] = useState<any>(null);
  const [layers, setLayers] = useState<LayerConfig[]>([
    { id: 'poi_main', name: '主要景点', icon: <MapPin size={16} />, color: '#E74C3C', visible: true },
    { id: 'poi_food', name: '餐饮美食', icon: <Utensils size={16} />, color: '#27AE60', visible: true },
    { id: 'photo_spots', name: '拍照点', icon: <Camera size={16} />, color: '#F39C12', visible: true },
    { id: 'routes', name: '路线', icon: <Route size={16} />, color: '#4A90E2', visible: true },
    { id: 'backup', name: '备选方案', icon: <Home size={16} />, color: '#8B7D6B', visible: false },
  ]);

  // 创建自定义图标
  const createCustomIcon = (color: string, iconType: string) => {
    const iconHtml = `
      <div style="
        background-color: ${color};
        width: 30px;
        height: 30px;
        border-radius: 50%;
        border: 3px solid white;
        box-shadow: 0 2px 8px rgba(0,0,0,0.3);
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 14px;
      ">
        ${getIconSymbol(iconType)}
      </div>
    `;
    
    return L.divIcon({
      html: iconHtml,
      className: 'custom-marker',
      iconSize: [30, 30],
      iconAnchor: [15, 15],
      popupAnchor: [0, -15]
    });
  };

  const getIconSymbol = (iconType: string) => {
    switch (iconType) {
      case 'poi_main': return '🏛️';
      case 'poi_food': return '🍜';
      case 'photo_spots': return '📷';
      case 'backup': return '🏠';
      default: return '📍';
    }
  };

  // 初始化地图
  useEffect(() => {
    if (!mapRef.current || mapInstanceRef.current) return;

    // 创建地图实例
    const map = L.map(mapRef.current, {
      center: [32.0503, 118.7969], // 南京市中心
      zoom: 12,
      zoomControl: false
    });

    // 添加缩放控件到右下角
    L.control.zoom({ position: 'bottomright' }).addTo(map);

    // 添加地图图层
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '© OpenStreetMap contributors',
      maxZoom: 18
    }).addTo(map);

    mapInstanceRef.current = map;

    // 初始化图层组
    layers.forEach(layer => {
      layerGroupsRef.current[layer.id] = L.layerGroup();
      if (layer.visible) {
        layerGroupsRef.current[layer.id].addTo(map);
      }
    });

    // 加载数据
    loadMapData();

    return () => {
      if (mapInstanceRef.current) {
        mapInstanceRef.current.remove();
        mapInstanceRef.current = null;
      }
    };
  }, []);

  // 加载地图数据
  const loadMapData = async () => {
    try {
      // 加载主要景点
      const poiMainResponse = await fetch('/src/data/poi_main.json');
      const poiMainData = await poiMainResponse.json();
      addMarkersToLayer('poi_main', poiMainData.features, '#E74C3C');

      // 加载餐饮数据
      const poiFoodResponse = await fetch('/src/data/poi_food.json');
      const poiFoodData = await poiFoodResponse.json();
      addMarkersToLayer('poi_food', poiFoodData.features, '#27AE60');

      // 加载拍照点
      const photoSpotsResponse = await fetch('/src/data/photo_spots.json');
      const photoSpotsData = await photoSpotsResponse.json();
      addMarkersToLayer('photo_spots', photoSpotsData.features, '#F39C12');

      // 加载路线
      const routesResponse = await fetch('/src/data/routes.json');
      const routesData = await routesResponse.json();
      addRoutesToLayer('routes', routesData.features, '#4A90E2');

      // 加载备选方案
      const backupResponse = await fetch('/src/data/backup.json');
      const backupData = await backupResponse.json();
      addMarkersToLayer('backup', backupData.features, '#8B7D6B');

    } catch (error) {
      console.error('加载地图数据失败:', error);
    }
  };

  // 添加标记到图层
  const addMarkersToLayer = (layerId: string, features: any[], color: string) => {
    const layerGroup = layerGroupsRef.current[layerId];
    if (!layerGroup) return;

    features.forEach(feature => {
      const [lng, lat] = feature.geometry.coordinates;
      const marker = L.marker([lat, lng], {
        icon: createCustomIcon(color, layerId)
      });

      // 创建弹窗内容
      const popupContent = createPopupContent(feature.properties, layerId);
      marker.bindPopup(popupContent, {
        maxWidth: 300,
        className: 'custom-popup'
      });

      // 点击事件
      marker.on('click', () => {
        setSelectedPoi(feature.properties);
      });

      layerGroup.addLayer(marker);
    });
  };

  // 添加路线到图层
  const addRoutesToLayer = (layerId: string, features: any[], color: string) => {
    const layerGroup = layerGroupsRef.current[layerId];
    if (!layerGroup) return;

    features.forEach(feature => {
      const coordinates = feature.geometry.coordinates.map((coord: number[]) => [coord[1], coord[0]]);
      const polyline = L.polyline(coordinates, {
        color: color,
        weight: 4,
        opacity: 0.8
      });

      // 添加路线信息弹窗
      const popupContent = `
        <div class="p-3">
          <h3 class="font-bold text-lg mb-2">${feature.properties.start_name} → ${feature.properties.end_name}</h3>
          <div class="space-y-1 text-sm">
            <p><span class="font-semibold">交通方式:</span> ${feature.properties.mode === 'walk' ? '步行' : feature.properties.mode === 'metro' ? '地铁' : feature.properties.mode === 'bus' ? '公交' : '打车'}</p>
            <p><span class="font-semibold">距离:</span> ${feature.properties.distance}</p>
            <p><span class="font-semibold">时间:</span> ${feature.properties.duration}</p>
            <p><span class="font-semibold">费用:</span> ${feature.properties.cost}</p>
            <p class="mt-2">${feature.properties.instructions}</p>
          </div>
        </div>
      `;

      polyline.bindPopup(popupContent, {
        maxWidth: 300
      });

      layerGroup.addLayer(polyline);
    });
  };

  // 创建弹窗内容
  const createPopupContent = (properties: any, layerId: string) => {
    switch (layerId) {
      case 'poi_main':
        return `
          <div class="p-3">
            <h3 class="font-bold text-lg mb-2">${properties.name}</h3>
            <div class="space-y-1 text-sm">
              <p><span class="font-semibold">类型:</span> ${properties.category}</p>
              <p><span class="font-semibold">开放时间:</span> ${properties.open_hours}</p>
              <p><span class="font-semibold">门票:</span> ${properties.tickets}</p>
              <p><span class="font-semibold">游玩时长:</span> ${properties.visit_duration}</p>
              <p><span class="font-semibold">排队预估:</span> ${properties.queue_estimate}</p>
              <p class="mt-2">${properties.description}</p>
              ${properties.photo_tips ? `<p class="mt-2 text-blue-600"><span class="font-semibold">拍照建议:</span> ${properties.photo_tips}</p>` : ''}
            </div>
          </div>
        `;
      case 'poi_food':
        return `
          <div class="p-3">
            <h3 class="font-bold text-lg mb-2">${properties.name}</h3>
            <div class="space-y-1 text-sm">
              <p><span class="font-semibold">菜系:</span> ${properties.cuisine_type}</p>
              <p><span class="font-semibold">营业时间:</span> ${properties.business_hours}</p>
              <p><span class="font-semibold">人均消费:</span> ${properties.price_range}</p>
              <p><span class="font-semibold">等位时间:</span> ${properties.avg_wait_time}分钟</p>
              ${properties.specialties ? `<p><span class="font-semibold">招牌菜:</span> ${properties.specialties.join(', ')}</p>` : ''}
              <p class="mt-2">${properties.description}</p>
            </div>
          </div>
        `;
      case 'photo_spots':
        return `
          <div class="p-3">
            <h3 class="font-bold text-lg mb-2">${properties.name}</h3>
            <div class="space-y-1 text-sm">
              <p><span class="font-semibold">最佳时间:</span> ${properties.best_time}</p>
              <p><span class="font-semibold">拍摄方向:</span> ${properties.direction}</p>
              <p><span class="font-semibold">构图建议:</span> ${properties.composition_tips}</p>
              <p><span class="font-semibold">设备建议:</span> ${properties.equipment_suggest}</p>
              <p><span class="font-semibold">难度:</span> ${properties.difficulty}</p>
              <p class="mt-2">${properties.description}</p>
            </div>
          </div>
        `;
      case 'backup':
        return `
          <div class="p-3">
            <h3 class="font-bold text-lg mb-2">${properties.name}</h3>
            <div class="space-y-1 text-sm">
              <p><span class="font-semibold">类型:</span> ${properties.category}</p>
              <p><span class="font-semibold">适用场景:</span> ${properties.reason}</p>
              <p><span class="font-semibold">开放时间:</span> ${properties.open_hours}</p>
              <p><span class="font-semibold">游玩时长:</span> ${properties.visit_duration}</p>
              <p class="mt-2">${properties.description}</p>
              <p class="mt-2 text-orange-600">${properties.features}</p>
            </div>
          </div>
        `;
      default:
        return `<div class="p-3"><h3 class="font-bold">${properties.name}</h3></div>`;
    }
  };

  // 切换图层显示
  const toggleLayer = (layerId: string) => {
    const map = mapInstanceRef.current;
    const layerGroup = layerGroupsRef.current[layerId];
    if (!map || !layerGroup) return;

    setLayers(prev => prev.map(layer => {
      if (layer.id === layerId) {
        const newVisible = !layer.visible;
        if (newVisible) {
          layerGroup.addTo(map);
        } else {
          map.removeLayer(layerGroup);
        }
        return { ...layer, visible: newVisible };
      }
      return layer;
    }));
  };

  return (
    <div className={`relative ${className}`}>
      {/* 地图容器 */}
      <div ref={mapRef} className="w-full h-full rounded-lg overflow-hidden" />
      
      {/* 图层控制面板 */}
      <div className="absolute top-4 left-4 bg-white rounded-lg shadow-lg p-4 z-[1000]">
        <h3 className="font-bold text-sm mb-3 text-gray-800">地图图层</h3>
        <div className="space-y-2">
          {layers.map(layer => (
            <div key={layer.id} className="flex items-center space-x-2">
              <button
                onClick={() => toggleLayer(layer.id)}
                className={`flex items-center space-x-2 px-2 py-1 rounded text-xs transition-colors ${
                  layer.visible 
                    ? 'bg-blue-100 text-blue-800' 
                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                }`}
              >
                {layer.visible ? <Eye size={12} /> : <EyeOff size={12} />}
                <span style={{ color: layer.color }}>{layer.icon}</span>
                <span>{layer.name}</span>
              </button>
            </div>
          ))}
        </div>
      </div>

      {/* 选中POI详情面板 */}
      {selectedPoi && (
        <div className="absolute bottom-4 left-4 right-4 bg-white rounded-lg shadow-lg p-4 z-[1000] max-w-md mx-auto">
          <div className="flex justify-between items-start mb-2">
            <h3 className="font-bold text-lg">{selectedPoi.name}</h3>
            <button
              onClick={() => setSelectedPoi(null)}
              className="text-gray-400 hover:text-gray-600"
            >
              ✕
            </button>
          </div>
          <div className="text-sm text-gray-600">
            <p>{selectedPoi.description}</p>
            {selectedPoi.address && (
              <p className="mt-2"><span className="font-semibold">地址:</span> {selectedPoi.address}</p>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

export default Map;